<?php

namespace api\modules\backend\controllers;

use api\modules\backend\models\Hotel;
use yii\data\Pagination;
use common\commands\Common;
use Yii;
use yii\filters\auth\QueryParamAuth;

/**
 * Hotel Controller API
 *
 * @author Fong <xiaofeng.zhang@suppernovachina.com>
 */
class HotelController extends ControllerBase
{
    public $modelClass = 'api\modules\backend\models\Hotel';
    private $notDeleted = 0; //未删除状态
    private $deleted = 1; //已删除状态
    private $errorString; //错误信息

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => QueryParamAuth::className(),
            'optional' => [],
        ];
        $behaviors['authenticator']['except'] = ['options'];

        return $behaviors;
    }

    /**
     * 酒店列表
     */
    public function actionIndex()
    {
        $get = Yii::$app->request->get();

        $where = [
            'is_deleted' => $this->notDeleted
        ];
        $get['hotel_name'] = isset($get['hotel_name']) ? $get['hotel_name'] : '';
        if (isset($get['active']) && is_numeric($get['active'])) $where['active'] = $get['active'];

        $hotelModelClass = new Hotel();
        $hotelFields = array(
            'hotel_id',
            'hotel_name',
            'hotel_contact',
            'create_time',
            'update_time',
            'active'
        );
        $hotelQuery = $hotelModelClass::find()->select($hotelFields)->where($where)
            ->andwhere([
                'and',
                ['like', 'hotel_name', $get['hotel_name']],
            ]);

        $countQuery = clone $hotelQuery;
        $pages = new Pagination(['totalCount' => $countQuery->count()]);
        $hotel = $hotelQuery->offset($pages->offset)
            ->limit($pages->limit)
            ->orderBy(['update_time' => SORT_DESC, 'create_time' => SORT_DESC])
            ->asArray()
            ->all();

        $meta = array('totalCount' => (int)$pages->totalCount, 'perPage' => $pages->getPageSize(), 'pageCount' => $pages->getPageCount(), 'currentPage' => $pages->getPage() + 1);
        $result = array('item' => $hotel, '_meta' => $meta);

        $this->success($result);
    }

    /**
     * 新增酒店
     * @throws \yii\db\Exception
     */
    public function actionCreate()
    {
        $time = time();
        $hotelModelClass = new Hotel();
        $post = Yii::$app->request->post();

        $hotelModelClass->load($post, '');
        $hotelModelClass->create_time = $time;
        $hotelModelClass->update_time = $time;

        $tr = Yii::$app->db->beginTransaction();
        try {

            if (!$hotelModelClass->save()) {
                throw new \Exception('DATABASE_FAILED');
            }

            $tr->commit();

        } catch (\Exception $e) {
            $tr->rollBack();
            $this->response(Common::getPackedResponse(DATABASE_FAILED, Yii::t('app', $e->getMessage())));
        }

        $this->success(array('id' => (string)$hotelModelClass->hotel_id));
    }

    /**
     * 酒店详情
     */
    public function actionView()
    {
        $get = Yii::$app->request->get();

        $hotel_id = is_numeric($get['id']) ? $get['id'] : 0;

        $hotelModelClass = new Hotel();
        $hotelFields = [
            'hotel_id',
            'hotel_name',
            'hotel_address',
            'hotel_contact',
            'active'
        ];
        $hotel = $hotelModelClass::find()->select($hotelFields)
            ->where(['hotel_id' => $hotel_id, 'is_deleted' => $this->notDeleted])
            ->asArray()
            ->one();

        $data = array('hotel' => $hotel);
        $this->success($data);
    }

    /**
     * 更新酒店
     * @throws \yii\db\Exception
     */
    public function actionUpdate()
    {
        $get = Yii::$app->request->get();
        $post = Yii::$app->request->post();

        $hotel_id = is_numeric($get['id']) ? $get['id'] : 0;

        if (empty($hotel_id)) {
            $this->errorString = Yii::t('app', '{attribute} does not exist!', ['attribute' => Yii::t('app', 'hotel_id')]);
            $this->response(Common::getPackedResponse(DATABASE_FAILED, $this->errorString));
        }

        $hotelModelClass = new Hotel();
        $hotel = $hotelModelClass::findOne(['hotel_id' => $hotel_id, 'is_deleted' => $this->notDeleted]);

        if (empty($hotel)) {
            $this->errorString = Yii::t('app', '{attribute} does not exist!', ['attribute' => Yii::t('app', 'hotel')]);
            $this->response(Common::getPackedResponse(DATABASE_FAILED, $this->errorString));
        }

        $hotel->setAttributes($post);
        $hotel->update_time = time();

        if (!$hotel->validate()) {//验证数据
            $this->response(Common::getPackedResponse(DATABASE_FAILED, 'DATABASE_FAILED'));
        }

        $tr = Yii::$app->db->beginTransaction();//事务 如果失败 就会滚数据
        try {
            if (!$hotel->update()) {
                throw new \Exception('DATABASE_FAILED');
            }

            $tr->commit();
        } catch (\Exception $e) {
            $tr->rollBack();
            $this->response(Common::getPackedResponse(DATABASE_FAILED, 'DATABASE_FAILED'));
        }

        $this->success(array('hotel_id' => $hotel_id));
    }

    /**
     * 删除酒店
     * @throws \yii\db\Exception
     */
    public function actionDelete()
    {
        $get = Yii::$app->request->get();

        $hotel_id = is_numeric($get['id']) ? $get['id'] : 0;

        $hotelModelClass = new Hotel();
        $hotel = $hotelModelClass::findOne(['hotel_id' => $hotel_id, 'is_deleted' => $this->notDeleted]);

        if (empty($hotel)) {
            $this->response(Common::getPackedResponse(DATABASE_FAILED, 'DATABASE_FAILED'));
        }

        $hotel->is_deleted = $this->deleted;

        $tr = Yii::$app->db->beginTransaction();//事务 如果失败 就会滚数据
        try {

            if (!$hotel->update()) {
                throw new \Exception('DATABASE_FAILED');
            }

            $tr->commit();
        } catch (\Exception $e) {
            $tr->rollBack();
            $this->response(Common::getPackedResponse(DATABASE_FAILED, 'DATABASE_FAILED'));
        }

        $this->success(array('hotel_id' => $hotel_id));
    }
}